package com.yzk.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzk.train.business.entity.Station;
import com.yzk.train.business.entity.StationExample;
import com.yzk.train.business.mapper.StationMapper;
import com.yzk.train.business.request.StationQueryReq;
import com.yzk.train.business.request.StationSaveReq;
import com.yzk.train.business.response.StationQueryResp;
import com.yzk.train.common.exception.BusinessException;
import com.yzk.train.common.exception.ExceptionEnum;
import com.yzk.train.common.response.PageResp;
import com.yzk.train.common.utils.SnowUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StationService {

    @Resource
    private StationMapper stationMapper;

    /**
     * 保存 / 更新 车站
     * @param req
     */
    public String save(StationSaveReq req) {
        Station station = BeanUtil.copyProperties(req, Station.class);
        DateTime now = DateTime.now();
        station.setUpdateTime(now);
        if (ObjectUtil.isNull(station.getId())) {
            // 保存之前，校验唯一键是否存在
            StationExample stationExample = new StationExample();
            stationExample.createCriteria().andNameEqualTo(req.getName());
            List<Station> list = stationMapper.selectByExample(stationExample);
            if (CollUtil.isNotEmpty(list)) {
                throw new BusinessException(ExceptionEnum.BUSINESS_STATION_NAME_UNIQUE_ERROR);
            }

            station.setId(SnowUtil.getSnowflakeNextId());
            station.setCreateTime(now);
            stationMapper.insert(station);
            return "保存成功";
        } else {
            stationMapper.updateByPrimaryKeySelective(station);
            return "编辑成功";
        }
    }

    /**
     * 查询车站列表（分页）
     * @param req
     */
    public PageResp<StationQueryResp> queryList(StationQueryReq req) {
        StationExample stationExample = new StationExample();
        stationExample.setOrderByClause("id desc");
        // 如果有参，就按照 车站名称 / 车站名称拼音 / 首字母 查询
        if (StrUtil.isNotBlank(req.getKeyword())) {
            String keyword = "%" + req.getKeyword() + "%";
            if (req.getKeyword().matches("^[a-zA-Z]*")) {
                stationExample.or().andNamePinyinLike(keyword);
                stationExample.or().andNamePyLike(keyword);
            } else {
                stationExample.createCriteria().andNameLike(keyword);
            }
        }
        // 使用分页插件
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Station> stations = stationMapper.selectByExample(stationExample);
        // 使用 PageInfo 包装查询结果
        PageInfo<Station> pageInfo = new PageInfo<>(stations);
        // 转换为 PageResp
        List<StationQueryResp> list = BeanUtil.copyToList(stations, StationQueryResp.class);
        return new PageResp<>(pageInfo.getTotal(), list);
    }

    /**
     * 查询车站列表 （无分页）
     */
    public List<StationQueryResp> queryAll() {
        StationExample stationExample = new StationExample();
        stationExample.setOrderByClause("name_pinyin asc");
        List<Station> stations = stationMapper.selectByExample(stationExample);
        return BeanUtil.copyToList(stations, StationQueryResp.class);
    }

    /**
     * 根据ID删除车站
     * @param id
     */
    public void delete(Long id) {
        stationMapper.deleteByPrimaryKey(id);
    }

}
